package com.lucene;

import com.util.LucenceConfig;
import com.util.LucenceConvert;
import com.util.LucencePage;
import com.util.LucenceUtil;
import org.apache.commons.io.FileUtils;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * lucence 工具类测试
 *
 * @author hutongfu
 * @since 2018-01-08 13:57
 */
public class IndexUtilTest {

    @Test
    public void testAddIndex() throws IOException {

        //指定文件所在的目录
        File dir = new File("E:\\maven_workspace\\lucence\\file");
        for (File file : dir.listFiles()) {
            String fileName = file.getName();
            String fileContext = FileUtils.readFileToString(file);
            long fileSize = FileUtils.sizeOf(file);

            Document document = new Document();

            //创建域
            TextField nameField = new TextField("fileName", fileName, Field.Store.YES);
            TextField contextField = new TextField("fileContext", fileContext, Field.Store.NO);
            LongField sizeField = new LongField("fileSize", fileSize, Field.Store.YES);

            //
            document.add(nameField);
            document.add(contextField);
            document.add(sizeField);

            //创建索引
            LucenceUtil.addIndex(document);
        }
    }

    @Test
    public void testSearchIndex() throws ParseException {
        LucencePage page = new LucencePage<>();
        //创建查询语句对象。第一个参数【默认搜索域】、第二个参数【分词器】
        QueryParser queryParser = new QueryParser("fileName", LucenceConfig.getIkAnalyzer());
        //查询语法=域名：搜索的关键字
        Query query = queryParser.parse("fileName:test");

        LucenceConvert<FileObject> convert = new LucenceConvert<FileObject>() {
            @Override
            public FileObject documentToObj(Document document) {
                FileObject fileObject = new FileObject();
                fileObject.setFileName(document.get("fileName"));
                fileObject.setFileContext(document.get("fileContext"));
                fileObject.setFileSize(Long.valueOf(document.get("fileSize")));
                return fileObject;
            }

            @Override
            public Document objToDocument(FileObject fileObject) {
                Document document = new Document();
                return null;
            }
        };
        LucencePage<FileObject> page1 = LucenceUtil.findPage(page, query, convert);
        System.out.println(page1);
    }
}
